package com.xyingsoft.zp.zP_Board.listeners;

import com.xyingsoft.zp.zP_Board.manager.DataManager;
import com.xyingsoft.zp.zP_Board.manager.PlayerData;
import com.xyingsoft.zp.zP_Board.manager.ScoreboardManager;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;

public class PlayerEventListener implements Listener {
    private final Plugin plugin;
    private final DataManager dataManager;
    private final ScoreboardManager scoreboardManager;
    
    public PlayerEventListener(Plugin plugin, DataManager dataManager, ScoreboardManager scoreboardManager) {
        this.plugin = plugin;
        this.dataManager = dataManager;
        this.scoreboardManager = scoreboardManager;
    }
    
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        // 确保玩家有数据记录
        dataManager.getPlayerData(player);
        // 立即更新玩家的计分板
        scoreboardManager.updateScoreboard(player);
    }
    
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        // 玩家退出时保存数据
        dataManager.saveAllData();
    }
    
    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        if (event.isCancelled()) return;
        
        Player player = event.getPlayer();
        PlayerData data = dataManager.getPlayerData(player);
        data.incrementBlocksBreak();
    }
    
    @EventHandler
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();
        PlayerData data = dataManager.getPlayerData(player);
        data.incrementDeaths();
        
        // 如果是被其他玩家杀死的，增加击杀者的击杀数
        Player killer = player.getKiller();
        if (killer != null) {
            PlayerData killerData = dataManager.getPlayerData(killer);
            killerData.incrementKills();
        }
    }
    
    @EventHandler
    public void onEntityDeath(EntityDeathEvent event) {
        // 仅处理非玩家实体的死亡
        if (event.getEntityType() == EntityType.PLAYER) return;
        
        Player killer = event.getEntity().getKiller();
        if (killer != null) {
            PlayerData data = dataManager.getPlayerData(killer);
            data.incrementKills();
        }
    }
    
    @EventHandler
    public void onPlayerExpChange(PlayerExpChangeEvent event) {
        Player player = event.getPlayer();
        PlayerData data = dataManager.getPlayerData(player);
        data.addExperience(event.getAmount());
    }
} 